/*
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package net.javlov.example.cont;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;

import net.javlov.example.WorldView;


public class ContinuousWorldView extends WorldView {
	
	private static final long serialVersionUID = -193232841584505904L;
	
	protected ContinuousWorld model;
	
	protected int agentDim;
	protected double scale, agentRadius;
	
	public ContinuousWorldView(ContinuousWorld w) {
		setModel(w);
	}
	
	public ContinuousWorld getModel() {
		return model;
	}

	public void setModel(ContinuousWorld model) {
		this.model = model;
		modelWidth = model.getWidth();
		modelHeight = model.getHeight();
		agentRadius = model.agentRadius;
		scale = Math.ceil(10/agentRadius);
		System.out.println(scale);
		agentDim = (int)Math.round(2*agentRadius*scale);
		setPreferredSize(new Dimension((int)Math.round(modelWidth*scale), (int)Math.round(modelHeight*scale)));
	}
	
	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		Graphics2D g2d = (Graphics2D) g;
		saveXform = g2d.getTransform();
		g2d.transform(scaleXform);
		
		//draw background
		g2d.setColor(Color.white);
		g2d.fillRect(0, 0, (int)Math.round(modelWidth*scale), (int)Math.round(modelHeight*scale));

		//draw agent
		g2d.setColor(Color.black);
		double[] s = model.getCurrentState().getData();
		if ( s != null ) {
			//body
			g2d.drawOval((int)Math.round((s[0]-agentRadius)*scale), (int)Math.round((s[1]-agentRadius)*scale),
					agentDim, agentDim);
			//heading
			g2d.drawLine((int)Math.round(s[0]*scale), (int)Math.round(s[1]*scale),
					(int)Math.round((s[0]+agentRadius*Math.sin(s[2]))*scale), (int)Math.round((s[1]+agentRadius*Math.cos(s[2]))*scale));
		}
		
		//draw goal
		s = model.getGoalState().getData();
		if ( s != null ) {			
			g2d.drawLine((int)Math.round(s[0]*scale), (int)Math.round(s[1]*scale),
					(int)Math.round(s[0]*scale+agentDim), (int)Math.round(s[1]*scale+agentDim));
			g2d.drawLine((int)Math.round(s[0]*scale+agentDim), (int)Math.round(s[1]*scale),
					(int)Math.round(s[0]*scale), (int)Math.round(s[1]*scale+agentDim));
		}
		
		drawOthers(g2d);
		
		//return to original transform
		g2d.setTransform(saveXform);
	}

}
